package DigitalNetwork;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.beans.*;
import java.util.ArrayList;
import java.util.ListIterator;
import javax.swing.GroupLayout.Alignment;

/**
 * A program belepesi pontja. Itt kezelodnek le a felhasznalo
 * altal kiadott parancsok.
 *
 * @author Kamaras Karoly
 * @author Andrasi Istvan
 * @author Pora Szilard
 * @author Ableda Peter
 *
 * @version 1.0 Build 2011.04.17
 */
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class Main implements Runnable, ActionListener, PropertyChangeListener {

	/** A program fo halozat objektuma */
	public NetworkController networkController;
	// GUI elemek
	private javax.swing.JButton loadNetworkButton;
	private javax.swing.JButton startStopButton;
	private javax.swing.JButton stepButton;
	private javax.swing.JButton setInputsButton;
	public static javax.swing.JLabel stateLabel;
	private javax.swing.JSeparator separator1;
	private javax.swing.JSeparator separator2;
	private javax.swing.JPanel menuPanel;
	public static NetworkView drawPanel;
	private javax.swing.JPanel statusPanel;

	/**
	 * Ablak komponenseinek inicializalasa
	 */
	//==========================================================================
	private void initComponents() {
		loadNetworkButton = new javax.swing.JButton("Load network");
		loadNetworkButton.setActionCommand("loadNetworkButton");
		loadNetworkButton.addActionListener(this);

		startStopButton = new javax.swing.JButton("Start/Stop");
		startStopButton.setActionCommand("startStopButton");
		startStopButton.addActionListener(this);

		stepButton = new javax.swing.JButton("Step");
		stepButton.setActionCommand("stepButton");
		stepButton.addActionListener(this);

		setInputsButton = new javax.swing.JButton("Set inputs");
		setInputsButton.setActionCommand("setInputsButton");
		setInputsButton.addActionListener(this);

		stateLabel = new javax.swing.JLabel("Statusz");
		separator1 = new javax.swing.JSeparator();
		separator2 = new javax.swing.JSeparator();
		drawPanel = new NetworkView();

		networkController = new NetworkController();
	}
	//==========================================================================

	//==========================================================================
	public void run() {
		initComponents();
		JFrame frame = new JFrame();

		// Menu panel
		menuPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		menuPanel.add(loadNetworkButton);
		menuPanel.add(startStopButton);
		menuPanel.add(stepButton);
		menuPanel.add(setInputsButton);

		// Frame
		frame.add(menuPanel, BorderLayout.NORTH);
		drawPanel.setPreferredSize(new Dimension(600, 600));
		frame.add(drawPanel, BorderLayout.CENTER);
		frame.add(stateLabel, BorderLayout.SOUTH);

		frame.validate();
		frame.pack();
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.setTitle("DigitalNetwork by SIKS 2011");
		frame.setVisible(true);
	}
	//==========================================================================

	//==========================================================================
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("loadNetworkButton")) {
			stateLabel.setText("Load network");
			String input = (String) JOptionPane.showInputDialog(
				new JFrame(),
				"Insert the name of the network file:",
				"Load network",
				JOptionPane.PLAIN_MESSAGE);

			if (input == null || input.equals("")) {
				Main.stateLabel.setText("[INFO] Betoltes leallitva");
			} else {
				networkController.load(input);
			}
		} else if (e.getActionCommand().equals("startStopButton")) {
			stateLabel.setText("Start/Stop");
			networkController.startStop();
		} else if (e.getActionCommand().equals("stepButton")) {
			stateLabel.setText("Step");
			networkController.step();
		} else if (e.getActionCommand().equals("setInputsButton")) {
			stateLabel.setText("Set inputs");
            
            JComponent[] inputs = null;
            if(networkController.getNetwork() != null){
                int size = networkController.getNetwork().simulator.sources.size();
                inputs = new JComponent[size*2];
                
                // Vegigmegyunk az osszesz Source-on es kiolvassuk a bemenetek ertekeit es az ID-ket
                for(int i=0; i<size; i++){
                    Source s = (Source)networkController.getNetwork().simulator.sources.get(i);
                    
                    // Label beallitasa a bemenet nevere
                    JLabel l = new JLabel(s.getID());
                    l.setName(s.getID());
                    inputs[2*i] = l;
                    
                    // TextField beallitasa a bemenet erteke alapjan
                    JTextField tf = new JTextField();
                    tf.setName(s.getID());
                    if(s.getType().equals("Button")){
                        Button b = (Button)s;
                        tf.setText(b.getIsHigh() ? "1" : "0");
                    } else if(s.getType().equals("Generator")){
                        Generator gen = (Generator)s;
                        tf.setText(gen.getPattern());
                    }
                    inputs[2*i+1] = tf;
                }
                // Felugro ablak a bemenetek beallitasaira
                JOptionPane.showMessageDialog(null, inputs, "Set inputs", JOptionPane.PLAIN_MESSAGE);

                // Bekert ertekek beallitasa, es atadasa a setInputs-nak
                String[] settings = new String[inputs.length];
                for(int i=0; i<inputs.length/2; i++){
                    JLabel l = (JLabel)inputs[2*i];
                    JTextField tf = (JTextField)inputs[2*i+1];

                    settings[2*i] = l.getName();
                    settings[2*i+1] = tf.getText();
                }
                networkController.setInputs(settings);
            } else {
                stateLabel.setText("[HIBA] Nem talalhato bemenet.");
            }            
		}
	}
	//==========================================================================

	//==========================================================================
	public void propertyChange(PropertyChangeEvent evt) {
		throw new UnsupportedOperationException("Not supported yet.");
	}
	//==========================================================================

	/**
	 * Kiir egy uzenetet a kimenetre, es ha a file-ba iras engedelyezett, akkor
	 * abba is.
	 */
	//==========================================================================
	public static void printMessage(String message) {
		// Debug uzenet a standard kimeneten
		System.out.println(message);
	}
	//==========================================================================

	/**
	 * Egy beolvasott file kovetkezo nem ures sorat adja vissza.
	 *
	 * @return line Egy nem ures sor
	 */
	//==========================================================================
	public static String readNextLine(BufferedReader inp) throws IOException {
		try {
			// A kovetkezo nem ures sor megkeresese
			String line = inp.readLine();
			while ((line != null) && (line.length() == 0)) {
				line = inp.readLine();
			}
			if (line != null) {
				return line;
			}
			return null;
		} catch (IOException ioe) {
			Main.printMessage("#[HIBA] " + ioe.getMessage());
			return null;
		}
	}
	//==========================================================================

	/** [Belepesi pont]
	 * @param args program inditasi parameterek.
	 */
	//==========================================================================
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Main());
	}
	//==========================================================================
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

